import { useState } from "react";
import { Form, message } from "antd";
import { IRole } from "@/api/interface/role";
import { createRole, updateRole } from "@/api/modules/role";

const useCreateRole = (getRoles: Function) => {
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [form] = Form.useForm();
	const [submitting, setSubmitting] = useState(false);
	const [editId, setEditId] = useState<number | null>(null);
	const onFinish = () => {
		form.resetFields();
	};
	const createModal = () => {
		form.resetFields();
		setIsModalOpen(true);
	};

	const handleOk = () => {
		setIsModalOpen(false);
	};

	const handleCancel = () => {
		setEditId(null);
		setIsModalOpen(false);
	};

	const editorForm = (formData: IRole) => {
		form.setFieldsValue(formData);
		setEditId(formData.id);
		console.log(formData);
		setIsModalOpen(true);
	};

	const handleSubmit = async () => {
		try {
			await form.validateFields();
			setSubmitting(true);
			const values = await form.getFieldsValue();
			let submitFn: Function = createRole;
			console.log(values);
			const params = {
				...values
			};
			console.log(editId);
			if (editId) {
				params.id = editId;
				submitFn = updateRole;
			}

			const { code, msg } = await submitFn(params);
			if (code === 200) {
				await getRoles();
				message.success(msg);
				handleCancel();
				form.resetFields();
			}

			setSubmitting(false);
		} catch (err) {
			setSubmitting(false);
			console.log(err);
		}
	};

	return {
		form,
		isModalOpen,
		submitting,
		onFinish,
		createModal,
		handleOk,
		editorForm,
		handleSubmit,
		handleCancel
	};
};
export default useCreateRole;
